·
<!-- 车间管理 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="status">
        <el-tag>{{ row.status ? '是' : '否' }}</el-tag>
      </template>
      <template slot="menuLeft"> </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.testDataCollection_view" @click="viewDetail(row)">详情</el-button>
      </template>
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="" slot="partNoSearch">
        <el-input placeholder="请选择 产品编码" readonly="true" v-model="search.partNo">
          <el-button slot="append" icon="el-icon-search" @click="openPartNoCommonModal"></el-button>
        </el-input>
      </template>
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-download" v-preventReClick v-if="permission.testDataCollection_export" @click="handleExport">导出</el-button>
      </template>
    </avue-crud>
    <el-dialog class="dialog" v-dragDirectives ref="dialog" title="详情" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <div class="custom-title"><i class="el-icon-vertical-bar mr10"></i>基本信息</div>
      <avue-form v-model="testDataDetail" :option="testDataDetailOption"></avue-form>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>测试数据</h3>
      <avue-crud :option="testDataDetailListOption" :table-loading="loading" :data="testDataDetailResult"></avue-crud>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>附件</h3>
      <div style="display: flex; width: 100%; height: 200px; overflow: auto" v-html="fileListHtml"></div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-product/machine-test-data/page" :option="option" :page="page" :query="query" file-name="采集信息"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail, exportMachineTestResult } from '@/api/report/test-data-collection';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getToken } from '@/util/auth';
import { downloadExcel } from '@/util/util';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
// import exportComp from '@/components/export-comp';
export default {
  name: 'ReportTestDataCollection',
  components: {
    CommonModalTemplate,
    userTableConfig
    // exportComp
  },
  mixins: [userConfig()],
  data() {
    var createTimeValidate = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请选择过站时间'));
      } else if (value) {
        let createTimeStart = this.$moment(value[0]).format('yyyy-MM-dd hh:mm:ss');
        let createTimeEnd = this.$moment(value[1]).format('yyyy-MM-dd hh:mm:ss');
        let createTimeStartGetTime = new Date(createTimeStart).getTime();
        let createTimeEndGetTime = new Date(createTimeEnd).getTime();
        let monthTime = 24 * 3600 * 1000 * 30;
        if (createTimeEndGetTime - createTimeStartGetTime > monthTime) {
          callback(new Error('过站时间范围请选择一个月内'));
        } else {
          callback();
        }
      }
    };
    return {
      pageCode: 'TEST_DATA_COLLECTION',
      visibile: false,
      modalName: '', //打开公用模态框名称
      form: {},
      defaults: {},
      query: {
        createTimeStart: this.getDefaultTime()[0],
        createTimeEnd: this.getDefaultTime()[1]
      },
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {
        creatTime: this.getDefaultTime()
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        labelWidth: 100,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        searchLabelWidth: 100,
        searchMenuPosition: 'right',
        columnBtn: false,
        column: [
          {
            label: '产品序列号',
            prop: 'sequenceNumber',
            search: true
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: '过站工序',
            prop: 'routeName',
            type: 'select',
            search: true,
            dicUrl: '/api/mes-product/apaasworkstation/workstation/list',
            props: {
              label: 'name',
              value: 'name'
            }
          },
          {
            label: '工序类型',
            prop: 'routeType',
            type: 'select',
            dicData: [
              {
                label: '过站工站',
                value: 'OVERSTATION'
              },
              {
                label: '组装工站',
                value: 'ASSEMBLY'
              },
              {
                label: '测试工站',
                value: 'TEST'
              },
              {
                label: '包装工站',
                value: 'PACKING'
              },
              {
                label: '老化工站',
                value: 'AGING'
              },
              {
                label: '报工工站',
                value: 'TIMESHEET'
              },
              {
                label: '上料工站',
                value: 'FEEDING'
              }
            ]
          },
          {
            label: '过站工位',
            prop: 'stationName',
            search: true
          },
          {
            label: '机台编码',
            prop: 'machineCode',
            search: true
          },
          {
            label: '测试结果',
            prop: 'result',
            search: true,
            type: 'select',
            dicData: [
              {
                label: 'PASS',
                value: 'PASS'
              },
              {
                label: 'FAIL',
                value: 'FAIL'
              }
            ]
          },
          {
            label: '过站时间',
            prop: 'createTime',
            search: true,
            searchSpan: 6,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '过站开始时间',
            endPlaceholder: '过站结束时间',
            searchValue: this.getDefaultTime(),
            // hide: true,
            searchRules: [
              {
                required: true,
                validator: createTimeValidate,
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '过站时间',
          //   prop: 'createTime'
          // },
          {
            label: '操作人',
            prop: 'operatorName',
            search: true
          }
        ]
      },
      data: [],
      showDialog: false,
      testDataDetail: {},
      testDataDetailOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '产品序列号',
            prop: 'sequenceNumber',
            disabled: true
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            disabled: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            disabled: true
          },
          {
            label: '过站工序',
            prop: 'routeName',
            disabled: true
          },
          {
            label: '测试结果',
            prop: 'result',
            disabled: true
          }
        ]
      },
      testDataDetailListOption: {
        height: '200',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 100,
        border: true,
        index: true,
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        indexLabel: '序号',
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        addBtn: false,
        column: []
      },
      testDataDetailResult: [],
      timer: new Date().getTime(),
      tableOption: {},
      fileListHtml: ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      let urlQuery = this.$route.query;
      if (urlQuery && urlQuery.sequenceNumber && urlQuery.createTime && urlQuery.machineCode && urlQuery.result) {
        this.search.sequenceNumber = decodeURIComponent(urlQuery.sequenceNumber);
        this.search.machineCode = decodeURIComponent(urlQuery.machineCode);
        this.search.result = decodeURIComponent(urlQuery.result);
        let createTimes = decodeURIComponent(urlQuery.createTime);
        if (createTimes) {
          this.search.createTimes = [createTimes, createTimes];
        }
      }
    });
    window.handleDownload = this.handleDownload;
    window.openPreview = this.openPreview;
  },
  methods: {
    initData(tenantId) {},
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      console.log(params);
      if (params.createTime && params.createTime.length > 0) {
        params.createTimeStart = params.createTime[0];
        params.createTimeEnd = params.createTime[1];
        delete params.createTime;
      }
      if (params.deptId) {
        params.deptName = params.deptId;
        delete params.deptId;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 下载
    openDownload(row) {
      if (row.fileUrl) {
        this.globalStartLoad('文件下载中，请稍后...');
        downloadFileByUrl(row.fileUrl, row.fileName);
        this.globalEndLoad();
      }
    },

    viewDetail(row) {
      this.showDialog = true;
      this.testDataDetail = row;
      this.testDataDetailResult = [];
      this.testDataDetailListOption.column = [];
      getDetail(row.id).then((res) => {
        let result = this._get(res, 'data.data[0].resultJson', '');
        if (result && result != null) {
          result = JSON.parse(result);
          for (const key in result) {
            this.testDataDetailListOption.column.push({
              label: key,
              prop: key
            });
          }
          this._forEach(res.data.data, (item) => {
            if (item.resultJson && item.resultJson != null) {
              this.testDataDetailResult.push(JSON.parse(item.resultJson));
            }
          });
        }
        let attachmentsHtml = this._get(res, 'data.data[0].attachments', '');
        if (attachmentsHtml && attachmentsHtml != null) {
          attachmentsHtml = JSON.parse(attachmentsHtml);
          let str = '';
          this._forEach(attachmentsHtml, (item, index) => {
            if (item.originalName.includes('.png') || item.originalName.includes('.jpg') || item.originalName.includes('.jpeg')) {
              str =
                str +
                `<div style="width: 200px;margin: 5px 10px">
                    <image src="${item.link}" onclick="openPreview('0', '${item.link}')" style="width: 100px;height:100px"></image>
                    <div>${item.originalName}</div>
                    <button type="button" class="el-button el-button--text el-button--small downLoadFile${index}" onclick="handleDownload('${item.link}')"><i class="el-icon-download"></i><span>下载</span></button>
                  </div>`;
            } else {
              str =
                str +
                `<div style="width: 200px;margin: 5px 10px">
                    <div>${item.originalName}</div>
                    <button type="button" class="el-button el-button--text el-button--small downLoadFile${index}" onclick="handleDownload('${item.link}')"><i class="el-icon-download"></i><span>下载</span></button>
                  </div>`;
            }
          });
          this.fileListHtml = str;
        }
      });
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择操作人员（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderTypeDesc'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    openPartNoCommonModal() {
      this.modalName = 'partNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'workOrderNoModal') {
        this.search.workOrderId = this._get(rowData, 'id', '');
        this.search.workOrderNo = this._get(rowData, 'orderNo', '');
      } else {
        this.search.partId = this._get(rowData, 'id', '');
        this.search.partNo = this._get(rowData, 'partNo', '');
      }
    },
    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    /**
     * 导出
     */
    handleExport() {
      exportMachineTestResult({ ...this.query })
        .then((res) => {
          this.$message.success(res.data.msg);
          // downloadExcel(res.data, '采集信息' + new Date().toLocaleString());
          // this.$message({
          //   type: 'success',
          //   message: '导出成功！'
          // });
        })
        .catch((e) => {
          this.$message.error('系统错误,请联系管理员!');
        });
    },
    getDefaultTime() {
      const startTime = this.$moment(new Date()).subtract(7, 'days').format('yyyy-MM-DD HH:mm:ss');
      const endTime = this.$moment(new Date()).format('yyyy-MM-DD HH:mm:ss');
      return [startTime, endTime];
    }
  }
};
</script>

<style lang="scss" scoped>
.custom-title {
  font-size: 17px;
  font-weight: bold;
  margin-bottom: 20px;
  i {
    margin-right: 10px;
  }
}
.dialog {
  ::v-deep .el-form {
    .avue-form__menu {
      display: none !important;
    }
  }
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
</style>
